package com.remote.ui.core.manager;

import com.remote.common.context.listener.ReadListener;
import com.remote.ui.core.Controller;
import com.remote.ui.core.ControllerManager;
import com.remote.ui.core.ControllerStarter;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AppControllerStarter implements ControllerStarter {
    private final Parent parent;
    private final String fxml;
    private final FXMLLoader loader;
    private final List<String> iconPaths = new ArrayList<>();
    private final ControllerManager controllerManager;

    private Object controller;
    private Stage stage;
    private Scene scene;


    public AppControllerStarter(ControllerManager controllerManager, String fxml) throws IOException {
        this.controllerManager = controllerManager;
        this.fxml = fxml;
        this.loader = new FXMLLoader(getClass().getResource(fxml));
        this.parent = (Parent) this.loader.load();
    }

    @Override
    public ControllerStarter show(String title) {
        show(title, new HashMap<>());
        return this;
    }

    @Override
    public ControllerStarter show(String title, Map<String, Object> vars) {
        //添加程序注释
        Scene scene = getScene();
        Stage stage = this.getStage();
        for (String iconPath : this.iconPaths) {
            stage.getIcons().addAll(new Image(iconPath));
        }
        if (this.controller == null) {
            this.controller = this.loader.getController();
            if (this.controller instanceof Controller) {
                ((Controller) this.controller).onCreate(this.controllerManager, scene, vars);
            }
        } else {
        }
        if (this.controller instanceof ReadListener) {
            if (!this.controllerManager.getCommandContext().getReadListeners().contains(this.controller)) {
                this.controllerManager.getCommandContext().addReadListener((ReadListener<?>) this.controller);
            }
        }
        stage.setTitle(title);
        stage.setScene(scene);
        stage.show();
        return this;
    }


    @Override
    public ControllerStarter addIcon(String iconPath) {
        this.iconPaths.add(iconPath);
        return this;
    }

    @Override
    public ControllerStarter setStage(Stage stage) {
        this.stage = stage;
        return this;
    }

    @Override
    public Stage getStage() {
        if (this.stage == null) {
            this.stage = new Stage();
        }
        return this.stage;
    }

    @Override
    public Scene getScene() {
        if (this.scene == null) {
            this.scene = new Scene(this.parent);
        }
        return this.scene;
    }
}
